// 创建用户相关的小仓库
import { defineStore } from 'pinia'
// 引入接口
import { reqLogin, reqLogout, reqUserInfo } from "@/myapi"
// 引入数据类型
import {
  loginFormData,
  loginResponseData,
  userInfoResponseData,
} from '@/myapi/type'
import type { UserState } from './types/type'
// 引入在本地存储中存储和读取数据的方法
// 引入路由(常量路由)
import { constantRoute } from '@/router/routes'
// 按需引入lodash
// @ts-ignore

// 定义一个过滤异步数组的方法
function filterAsyncRoute(asyncRoute: any, routes: any) {
  return asyncRoute.filter((item: any) => {
    if (routes.includes(item.name)) {
      if (item.children && item.children.length > 0) {
        item.children = filterAsyncRoute(item.children, routes)
      }
      return true
    }
  })
}

// 创建用户小仓库
const useUserStore = defineStore('User', {
  // 存储数据的地方
  state: (): UserState => {
    return {
      token: localStorage.getItem('TOKEN'),
      menuRoutes: constantRoute,
      avatar: '',
      userName: '',
      buttons: [],
      permissions: [],
    }
  },
  // 处理异步|逻辑的地方
  actions: {
    // 用户登录的方法
    async userLogin(data: loginFormData) {
      const result: loginResponseData = await reqLogin(data)
      if (result.code === 0) {
        // 存储token
        this.token = result.data.token as string
        this.permissions = result.data.permission as string[]
        // 本地存一份
        localStorage.setItem('TOKEN', result.data.token as string)
        localStorage.setItem('permissions', result.data.permission as string[])
        return 'ok'
      } else {
        return Promise.reject(new Error(result.message))
      }
    },
    // 获取用户信息的方法
    async userInfo() {
      const result: userInfoResponseData = await reqUserInfo()
      if (result.code === 0) {
        this.avatar = result.data.avatar
        this.userName = result.data.userName

        return 'ok'
      } else {
        return Promise.reject('获取用户信息失败')
      }
    },
    // 退出登录的方法
    async userLogout() {
      const result = await reqLogout()
      if (result.code === 0) {
        this.token = ''
        this.avatar = ''
        this.userName = ''
        localStorage.removeItem('TOKEN')
        localStorage.removeItem('permissions')
        return 'ok'
      } else {
        return Promise.reject('退出失败')
      }
    },
  },
  getters: {},
})
//参数持久化

export default useUserStore
